from flask import Flask, request, jsonify, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import logging

app = Flask(__name__)
# 使用SQLite内存数据库，无需安装外部数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 配置日志
logging.basicConfig(level=logging.DEBUG)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'


@app.route('/register.html')
def register_page():
    return render_template('register.html')


@app.route('/success')
def success():
    return render_template('success.html')


@app.route('/register', methods=['POST'])
def register():
    """注册新用户接口"""
    # 自动处理JSON或表单数据
    if request.content_type.startswith('application/json'):
        data = request.get_json()
    else:
        data = request.form

    username = data.get('username')
    email = data.get('email')

    # 记录请求数据和类型
    logging.debug(f"Request Content-Type: {request.headers.get('Content-Type')}")
    logging.debug(f"Received data: {data}")

    # 参数验证
    if not username or not email:
        return jsonify({"error": "Missing username or email"}), 400

    # 检查用户名是否存在
    if User.query.filter_by(username=username).first():
        return jsonify({"error": "Username already exists"}), 400

    # 创建新用户
    new_user = User(username=username, email=email)
    try:
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": f"Database error: {str(e)}"}), 500

    # 统一返回JSON响应，包含跳转URL
    return jsonify({
        "success": True,
        "message": "User created successfully",
        "user": {
            "username": new_user.username,
            "email": new_user.email
        },
        "redirect_url": url_for('success')
    }), 201


if __name__ == '__main__':
    # 创建数据库表
    with app.app_context():
        db.create_all()
    # 启动应用
    app.run(debug=True)